<?php
namespace app\api\controller\waimai;

use app\common\controller\ApiController;
use app\api\service\DeliveryService;
use think\exception\ValidateException;
use think\facade\Log;
use think\facade\Request;
use app\api\model\Shop;
use app\api\model\Order as OrderModel;

// 订单相关操作
class Order extends ApiController
{

    public $params;

    public function __construct()
    {
        $params = Request::post();

        if (!empty($params['sysNumber'])){
            $see_order =OrderModel::where('sys_number', $params['sysNumber'])->find();
            if (!empty($see_order)){
                $params['app_type']=get_app_type_str($see_order['app_type']);

                // 转闪送参数
                $params['issOrderNo']=$see_order['third_number'];
                $params['thirdOrderNo']=$see_order['call_number'];

                // 转达达参数
                $params['deliveryNo']=$see_order['third_number'];
                $params['order_id']=$see_order['call_number'];
            }
        }

        $this->params=$params;
    }

    //计费下单接口（带比价）
    //传调用方门店id   platformStoreId
    public function orderCalculateUnify()
    {
        $params = $this->params;

        try {
            validate([
                'platformStoreId'  => 'require', 
                'app_type'  => 'require', 
            ])->message([
                'platformStoreId.require'  => 'platformStoreId必须传递',     
                'app_type.require'  => 'app_type必须传递',     
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $where['appid']=$params['appid'];
        $where['platform_store_id']=$params['platformStoreId'];
        if(strpos($params['app_type'],'dev')){//测试下单
           $where['pro_dev']=1;
        }else{//正式下单
           $where['pro_dev']=2;
        }
        
        //通过调用方平台id 查询多个配送平台门店
        $Store=(new Shop)::where($where)
                ->select()
                ->toArray();

        if(empty($Store)){
           output_error('未查询到门店');
        }

        //遍历多平台 配送费并加入数组中
        $feeArray = [];
        foreach ($Store as $key => $value) {
            $params['app_type'] = get_app_type_str($value['app_type']);
            $params['storeId']=$value['store_id'];

            // 调用平台接口
            $service = new DeliveryService($params['app_type']);
            $result = $service->orderCalculate($params);

            // 将结果加入数组
            $feeArray[] = $result;
        }

        // 递归数组中 实际配送费totalFeeAfterSave 最小的结果并返回
        if (!empty($feeArray)) {
            $minFeeResult = null;
            foreach ($feeArray as $item) {
                // 确保结构完整
                if (isset($item['success']) && $item['success'] === true &&
                    isset($item['data']['totalFeeAfterSave'])) {
                    if ($minFeeResult === null ||
                        $item['data']['totalFeeAfterSave'] < $minFeeResult['data']['totalFeeAfterSave']) {
                        $minFeeResult = $item;
                    }
                }
            }
            $result=$minFeeResult;
        }
      
        if(isset($result["success"])&&$result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]??'请求失败');
        }
    }

    //订单计费(预下单)
    //直接传配送门店id   storeId
    public function orderCalculate()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->orderCalculate($params);
             
        } catch (\Exception $e) {
            output_error($result["msg"]??$e->getMessage());
            output_error($result["msg"]??'请求失败');
        }

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    // 提交订单
    public function orderPlace()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->orderPlace($params);
            
        } catch (\Exception $e) {
             output_error($result["msg"]??'请求失败');
        }

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }
    

    // 订单加价
    public function addition()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->addition($params);
            
        } catch (\Exception $e) {
             output_error($result["msg"]??'请求失败');
        }

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }
    
    //查询订单详情
    public function orderInfo()
    {
        
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->orderInfo($params);
            
        } catch (\Exception $e) {
             output_error($result["msg"]??'请求失败');
        }

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    //查询闪送员位置信息
    public function courierInfo(Request $request)
    {
        $params = $this->params;

        // 处理逻辑
        $service = new DeliveryService($params['app_type']);
        $result = $service->courierInfo($params);

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    //查询订单续重加价金额
    public function calculateOrderAddWeightFee()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->calculateOrderAddWeightFee($params);
            
        } catch (\Exception $e) {
             output_error($result["msg"]??'请求失败');
        }

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    //支付订单续重费用
    public function payAddWeightFee()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->payAddWeightFee($params);
            
        } catch (\Exception $e) {
             output_error($result["msg"]??'请求失败');
        }

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    //订单预取消
    public function preAbortOrder()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->preAbortOrder($params);
            
        } catch (\Exception $e) {
             output_error($result["msg"]??'请求失败');
        }

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    //订单取消
    public function abortOrder()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->abortOrder($params);
            
        } catch (\Exception $e) {
             output_error($result["msg"]??'请求失败');
        }

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    //修改收件人手机号
    public function updateToMobile()
    {

        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->updateToMobile($params);
            
        } catch (\Exception $e) {
             output_error($result["msg"]??'请求失败');
        }

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    //异步消息推送 1骑士申请取消订单通知
    public function messagePush()
    {

        $params = $this->params;

        try {
            if($params)
            {
                $data=json_decode($params,true);
                match ($data['messageType'])
                {
                    "1"=>Db::name('message')->insert(['type'=>1,'content'=>$data['messageBody']]),//todo 存储通知消息 统一操作 伪代码
                };
            }
        } catch (\Exception $e) {
            Log::error("骑士申请取消订单异常:".$e->getMessage()."回调信息:".$params);
        }
    }


    //商户确认物品已返还
    public function confirmGoodsReturn()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->confirmGoodsReturn($params);
        } catch (\Exception $e) {
            output_error($result["msg"]??'请求失败');
        }
        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }
    //商户审核骑士取消订单
    public function merchantExamine()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->merchantExamine($params);
        } catch (\Exception $e) {
            output_error($result["msg"]??'请求失败');
        }
        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    //获取骑士配送信息H5页面
    public function transporter()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->transporter($params);
        } catch (\Exception $e) {
            output_error($result["msg"]??'请求失败');
        }
        if($result["success"]){
            return json(['code'=>1,'data'=>$result['data']]);
        }else{
            output_error($result["msg"]);
        }
    }

    //更新取件码和货架号
    public function fetchCode()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->fetchCode($params);
        } catch (\Exception $e) {
             output_error($result["msg"]??'请求失败');
        }
        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    //商户确认售后单交接完成
    public function afterSale()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->afterSale($params);
        } catch (\Exception $e) {
             output_error($result["msg"]??'请求失败');
        }
        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    //订单取消原因
    public function cancelReasons()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->cancelReasons($params);

        } catch (\Exception $e) {
            output_error($result["msg"]??'请求失败');
        }

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    // 订单追单
    public function appendOrder()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->appendOrder($params);

        } catch (\Exception $e) {
            output_error($result["msg"]??'请求失败');
        }

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    //商家投诉原因
    public function complaint()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->complaint($params);

        } catch (\Exception $e) {
            output_error($result["msg"]??'请求失败');
        }

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }

    //商家投诉原因
    public function complaintReasons()
    {
        $params = $this->params;

        try {
            $service = new DeliveryService($params['app_type']);
            $result = $service->complaintReasons($params);

        } catch (\Exception $e) {
            output_error($result["msg"]??'请求失败');
        }

        if($result["success"]){
            output_success('success', $result['data']);
        }else{
            output_error($result["msg"]);
        }
    }
}